<template>
  <div>
    <div>
      <video ref="video" autoplay style="height: 300px"></video>
      <img
        :src="capturedPhoto"
        alt="拍摄的照片"
        v-if="capturedPhoto"
        style="width: 450px; height: 300px"
      />
    </div>
    <el-button @click="openCamera">打开摄像头</el-button>
    <el-button @click="capturePhoto">拍摄照片</el-button>
    <input type="file" ref="fileInput" accept="image/*" style="display: none" />
    <el-button @click="back">返回</el-button>
    <el-button @click="down">下载照片</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      capturedPhoto: null,
    };
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    // 打开摄像头
    openCamera() {
      const video = this.$refs.video;
      navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
        video.srcObject = stream;
      });
    },
    // 拍摄照片
    capturePhoto() {
      const video = this.$refs.video;
      const canvas = document.createElement("canvas");
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas
        .getContext("2d")
        .drawImage(video, 0, 0, canvas.width, canvas.height);
      this.capturedPhoto = canvas.toDataURL("image/jpeg");
      this.$emit('update', this.capturedPhoto)
    },
    down() {
      // 获取图片base64链接
      let image = this.capturedPhoto;
      this.imgSrc = image;
      const file = image;
      const time = new Date().valueOf();
      const name = time + ".png";
      const conversions = this.base64ToFile(file, name);
      const data = new FormData();
      data.append("file", conversions);
    },
    // base64图片转file的方法（base64图片, 设置生成file的文件名）
    base64ToFile(content, fileName) {
      var base64ToBlob = function (code) {
        let parts = code.split(";base64,");
        let contentType = parts[0].split(":")[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {
          type: contentType,
        });
      };
      let aLink = document.createElement("a");
      let blob = base64ToBlob(content); //new Blob([content]);
      console.log(blob,'bob');
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    },
  },
};
</script>